# ai_sop_system/sop_engine.py
from datetime import datetime
from typing import Dict, List, Any
from enum import Enum


class SOPDecision(Enum):
    SEND_MESSAGE = "send_message"
    HUMAN_INTERVENTION = "human_intervention"
    AUTOMATED_PROCESS = "automated_process"
    ESCALATE = "escalate"
    COMPLETE = "complete"


class SOPEngine:
    """SOP决策引擎"""

    def __init__(self):
        self.sop_templates = {}
        self.decision_rules = DecisionRules()
        self.label_system = LabelSystem()

    def analyze_and_label(self, cms_data: Dict[str, Any]) -> Dict[str, Any]:
        """分析数据并建立SOP标签"""
        print("🏷️ SOP引擎分析数据并建立标签...")

        # 数据分析
        analysis_result = self._analyze_user_data(cms_data)

        # 标签建立
        sop_labels = self.label_system.create_sop_labels(analysis_result)

        # 决策路径生成
        decision_path = self._generate_decision_path(analysis_result, sop_labels)

        result = {
            "analysis_result": analysis_result,
            "sop_labels": sop_labels,
            "decision_path": decision_path,
            "recommended_actions": self._get_recommended_actions(sop_labels),
            "risk_assessment": self._assess_risk(analysis_result)
        }

        print("✅ SOP标签建立完成")
        return result

    def _analyze_user_data(self, cms_data: Dict) -> Dict[str, Any]:
        """分析用户数据"""
        analysis = {
            "user_profile_analysis": self._analyze_user_profile(cms_data),
            "behavior_analysis": self._analyze_behavior(cms_data),
            "preference_analysis": self._analyze_preferences(cms_data),
            "context_analysis": self._analyze_context(cms_data),
            "capability_assessment": self._assess_user_capability(cms_data)
        }

        # 综合评分
        analysis["overall_score"] = self._calculate_overall_score(analysis)

        return analysis


class LabelSystem:
    """标签系统"""

    def create_sop_labels(self, analysis_result: Dict) -> Dict[str, Any]:
        """创建SOP标签"""
        labels = {
            "priority_level": self._determine_priority(analysis_result),
            "complexity_level": self._determine_complexity(analysis_result),
            "intervention_type": self._determine_intervention_type(analysis_result),
            "communication_style": self._determine_communication_style(analysis_result),
            "time_sensitivity": self._determine_time_sensitivity(analysis_result),
            "risk_category": self._determine_risk_category(analysis_result)
        }

        # 组合标签
        labels["composite_label"] = self._create_composite_label(labels)

        return labels

    def _determine_priority(self, analysis: Dict) -> str:
        """确定优先级"""
        score = analysis.get("overall_score", 0.5)
        if score > 0.8:
            return "high"
        elif score > 0.5:
            return "medium"
        else:
            return "low"

    def _determine_intervention_type(self, analysis: Dict) -> str:
        """确定干预类型"""
        capability = analysis.get("capability_assessment", {}).get("level", "medium")

        if capability == "low":
            return "guided_assistance"
        elif capability == "high":
            return "autonomous"
        else:
            return "supervised"


class DecisionRules:
    """决策规则"""

    def get_decision(self, sop_labels: Dict, context: Dict) -> SOPDecision:
        """获取决策"""
        # 基于标签的决策逻辑
        if sop_labels["risk_category"] == "high":
            return SOPDecision.HUMAN_INTERVENTION

        if sop_labels["priority_level"] == "high" and sop_labels["time_sensitivity"] == "high":
            return SOPDecision.SEND_MESSAGE

        if sop_labels["intervention_type"] == "autonomous":
            return SOPDecision.AUTOMATED_PROCESS

        return SOPDecision.SEND_MESSAGE